package com.zw.pdm.module.production.service;

import com.zw.pdm.constant.Constant;
import com.zw.pdm.entity.production.MakeChange;
import com.zw.pdm.entity.production.MakeResult;
import com.zw.pdm.entity.production.MakeSheet;
import com.zw.pdm.entity.rep.Change;
import com.zw.pdm.entity.rep.Plan;
import com.zw.pdm.entity.rep.VerifyProcess;
import com.zw.pdm.entity.sys.User;
import com.zw.pdm.module.production.mapper.MakeChangeMapper;
import com.zw.pdm.module.production.mapper.MakePlanMapper;
import com.zw.pdm.module.production.mapper.MakeResultMapper;
import com.zw.pdm.module.production.mapper.MakeSheetMapper;
import com.zw.pdm.module.production.model.MakeSheetModel;
import com.zw.pdm.module.production.repository.MakeChangeRepository;
import com.zw.pdm.module.production.repository.MakePlanRepository;
import com.zw.pdm.module.production.repository.MakeSheetRepository;
import com.zw.pdm.module.report.mapper.ChangeMapper;
import com.zw.pdm.module.report.mapper.PlanMapper;
import com.zw.pdm.module.report.mapper.SheetMapper;
import com.zw.pdm.module.report.mapper.VerifyProcessMapper;
import com.zw.pdm.module.report.repository.ChangeRepository;
import com.zw.pdm.module.report.repository.PlanRepository;
import com.zw.pdm.module.report.repository.SheetRepository;
import com.zw.pdm.module.report.repository.VerifyProcessRepository;
import com.zw.pdm.module.system.mapper.UserMapper;
import com.zw.pdm.module.system.service.LogService;
import com.zw.pdm.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

import static com.zw.pdm.util.BeanUtil.copy;


/**
 * @author mayongfeng
 * @version 1.0.0
 * @ClassName ProductionCheckService.java
 * @Description TODO
 * @createTime 2020年10月06日 16:43:00
 */
@Service
@SuppressWarnings("all")
public class ProductionCheckService {


    @Autowired
    private MakeSheetMapper makeSheetMapper;
    @Autowired
    private MakeSheetRepository makeSheetRepository;
    @Autowired
    private MakePlanMapper makePlanMapper;
    @Autowired
    private MakePlanRepository makePlanRepository;
    @Autowired
    private MakeChangeMapper makeChangeMapper;
    @Autowired
    private MakeChangeRepository makeChangeRepository;
    @Autowired
    private MakeResultMapper makeResultMapper;
    /***************************************************************/
    @Autowired
    private SheetMapper sheetMapper;
    @Autowired
    private SheetRepository sheetRepository;
    @Autowired
    private PlanMapper planMapper;
    @Autowired
    private PlanRepository planRepository;
    @Autowired
    private VerifyProcessMapper verifyProcessMapper;
    @Autowired
    private VerifyProcessRepository verifyProcessRepository;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ChangeRepository changeRepository;
    @Autowired
    private ChangeMapper changeMapper;
    @Autowired
    private LogService logService;

    /**
     * 按条件查询制作件审核
     */
    public List<MakeSheetModel> findWithReportCheck(MakeSheetModel makeSheetModel) {
        makeSheetModel.setVerifier(ShiroUtils.getUserId());
        return makeSheetMapper.findWithProductionCheck(makeSheetModel);
    }

    /**
     * 制作件清单的审核计划
     */
    @Transactional(rollbackFor = Exception.class)
    public int makeVerify(Integer id) {
        VerifyProcess vp = verifyProcessMapper.findMakeCurVpBySheetId(id);
        Date date = new Date();//为了存入相同的审批时间
        /** 判断是否最后审核 0=否， 1=是 */
        if (vp.getComp() == 1) {
            /** 如果是最后一步审核， 修改计划单状态， 添加或更新makeResul*/
            MakeSheet makeSheet = makeSheetRepository.getOne(id);
            List<MakeChange> bySheetId = makeChangeRepository.findBySheetId(id);
            /** 状态 1=未提交，2=已提交，3=被驳回，4=撤消，5=全部审核通过*/
            makeSheet.setStatus(Constant.STATUS_COMPLETE);
            /** 是否可以变更  0=否，1=是*/
            makeSheet.setMayChange(1);
            makeSheet.setVerifyTime(date);
            makeSheetRepository.saveAndFlush(makeSheet);
            /** 判断表单类型 1=原始，2=变更*/
            if (makeSheet.getSheetType() == 1) {
                /** 原始单的话直接添加到Make_result表*/
                makeSheetMapper.insertMakeResult(id);
                /** 变更单等领导审核完*/
            } else if (makeSheet.getSheetType() == 2) {
                /** 通过planId修改result表里面的数据*/
                makeChangeMapper.updateMakeResultByChangeAfter(id);
                /** 通过changeId修改result表里面的数据*/
                makeChangeMapper.updateMakeChangeResultByChangeAfter(id);

                for (MakeChange makeChange : bySheetId) {
                    /** 循环makeChange表里面的数据，根据change表里的technologyChange 工艺变更类型  -1=不变， 1=已变更，2=变更删除,3=变更增加判断如何往makeResult里面操作*/
                    if (makeChange.getTechnologyChange() == 3) {
                        makeSheetMapper.insertMakeChangeResult(id);
                        break;
                    }
                }
                for (MakeChange makeChange : bySheetId) {
                    /** 循环makeChange表里面的数据，根据change表里的technologyChange 工艺变更类型  -1=不变， 1=已变更，2=变更删除,3=变更增加判断如何往makeResult里面操作*/
                    if (makeChange.getTechnologyChange() == 2) {
                        makeSheetMapper.updateMakeChangeResult(id);
                        makeSheetMapper.updateMakePlanResult(id);
                        break;
                    }
                }

                //在排序之前将order_num修正一下通过pid找到修正后的order_num在修改
                for (MakeChange makeChange : bySheetId) {
                    if (makeChange.getTechnologyChange() == 3) {
                        MakeResult makeResultOrderNumById = makeResultMapper.findMakeResultOrderNumById(makeChange.getPid());
                        final int i = makeResultMapper.updateMakeResultByPidOrderNum(makeResultOrderNumById.getOrderNum(), makeResultOrderNumById.getId());
                    }
                }

                //序号重写排序
                List<MakeResult> listResult = makeSheetMapper.findMakeResultSheetId(id);
                Integer resultOrderNum = 0;
                if (!listResult.isEmpty()) {
                    for (MakeResult makeResult : listResult) {
                        resultOrderNum++;
                        makeResultMapper.updateMakeResultById(makeResult.getId(), resultOrderNum);
                    }
                }

            }
        } else {
            // 修改下一个审核节点为当前节点
            VerifyProcess nextVp = verifyProcessMapper.findMakeNextVp(vp);
            nextVp.setCur(1);
            verifyProcessRepository.saveAndFlush(nextVp);
        }
        logService.saveLog("审核制作件清单", "制作件清单ID：" + vp.getMakeSheetId());
        return verifyProcessMapper.updateMakeStatusAndCurAndTimeById(vp.getId(), 2, 0, date);
    }

    /**
     * 驳回制作件清单计划
     */
    @Transactional(rollbackFor = Exception.class)
    public int makeReject(MakeSheet sheet) {
        VerifyProcess vp = verifyProcessMapper.findMakeCurVpBySheetId(sheet.getId());
        logService.saveLog("驳回制作件清单计划单", "制作件清单ID：" + vp.getMakeSheetId());
        MakeSheet target = makeSheetRepository.getOne(sheet.getId());
        copy(sheet, target);
        if (vp.getStart() == 1) {
            // 如果为第一个审核节点，修改计划为未提交，删除所有审核结点
            target.setStatus(Constant.STATUS_REJECT);
            makeSheetRepository.saveAndFlush(target);
            return verifyProcessMapper.delByMakeSheetId(sheet.getId());
        } else {
            // 修改上一个审核节点为当前节点，并标识为驳回状态
            makeSheetRepository.saveAndFlush(target);
            VerifyProcess preVp = verifyProcessMapper.findMakePreVp(vp);
            preVp.setCur(1);
            preVp.setStatus(0);
            verifyProcessRepository.saveAndFlush(preVp);
            return verifyProcessMapper.updateMakeStatusAndCurAndTimeById(vp.getId(), 1, 0, null);
        }
    }

    /**
     * 修改审核人
     */
    public VerifyProcess editVerify(VerifyProcess verifyProcess) {
        VerifyProcess vp = verifyProcessRepository.getOne(verifyProcess.getId());
        VerifyProcess nextVp = verifyProcessMapper.findNextVp(vp);
        nextVp.setVerifier(verifyProcess.getVerifier());
        logService.saveLog("修改审核人", "");
        return verifyProcessRepository.saveAndFlush(nextVp);
    }

    /**
     * 查询部级审核人
     */
    public List<User> findVerifier() {
        return userMapper.findVerifier("部级");
    }

    /**
     * 撤消变更计划，
     * 如果所属主表下所有计划全部撤消， 要删除主表数据
     * 撤消的变更原始计划或原始变更还应该可以再次发起变更
     */
    @Transactional
    public int cancelChange(Integer id) {
        Change change = changeRepository.getOne(id);
        int i = changeMapper.updateResultByChangeBefore(change);
        if (i == 0) {
            return 0;
        }
        if (change.getChangeId() != null) {
            Change c = changeRepository.getOne(change.getChangeId());
            c.setAlreadyChange(0);
            changeRepository.saveAndFlush(c);
        } else if (change.getPlanId() != null) {
            Plan p = planRepository.getOne(change.getPlanId());
            p.setAlreadyChange(0);
            planRepository.saveAndFlush(p);
        }
        logService.saveLog("撤消变更计划", "变更计划ID：" + id);
        changeMapper.updateStatusById(id, 3);
        List<Change> changes = changeMapper.findBySheetId(change.getSheetId());
        if (changes.size() == 0) {
            sheetMapper.updateStatusById(change.getSheetId(), Constant.STATUS_DELETE);
        }
        return 1;
    }

    /**
     * 查询 变更详细
     */
    public List<Change> findChangeDetail(Change change) {
        return changeMapper.findChangeDetailList(change);
    }

    /** 修改提报人 */
    public int editInforer(Integer postUserId, Integer id) {
        MakeSheet makeSheet = makeSheetRepository.getOne(id);
        makeSheet.setPostUserId(postUserId);
        makeSheetRepository.saveAndFlush(makeSheet);
        logService.saveLog("修改制作件清单提报人", "");
        return 1;
    }
}
